<?php
class Thumb {
	public $webthumbApiEndpoint;
	public $debug = false;
	public $databasePath;

	public function addUrl($url,$size='small',$width=300,$height=300){
		$url = trim($url);
		if(!preg_match('/^http/i',$url)){
			$url = 'http://'.$url;
		}
		$handle = new Option();
		$handle->options->width = $width;
		$handle->options->height= $height;
		$handle->options->url = $url;
		$handle->options->size = $size;
		$this->item=$handle;
		return $handle;
	}

    public function submitRequests(){
		if(count($this->item) < 1){
			throw new Exception('no input url');
		}
		$request = new SpricityRequestSubmit();
		$request->handle = $this->item;
		$requestUrl = $request->setFullUrl();
		$response = $this->_transmitRequest($requestUrl);
		$this->_parseSubmitResponse($response);
		//dbg($requestUrl);
	}
	protected function _transmitRequest($request){
	    $http = new HTTPRequest($this->webthumbApiEndpoint);
        $http->requestTimeout = 200;
	    $http->verb = "POST";
	    $http->body = $request;

		$response = $http->sendRequest();
        if ($response->code == 302)
        {
            if ($this->debug) {
                echo "We have a redir, lets figure out where the ApiEndpoint has moved too and try again\n";
                echo "New endoing is: ".$response->headers->Location."\n";
            }
            $this->webthumbApiEndpoint = $response->headers->Location;
            return $this->_transmitRequest($request);
        }
		if($response->code == 700){
			if ($this->debug)
            {
                echo "We had an error the response object is\n";
                echo "#################\n";
                echo ($http->body);
                echo "#################\n";
            }
            throw new Exception("$http->body",$response->code);
		}
        if ($response->code != 200) {
            if ($this->debug)
            {
                echo "We had an error the response object is\n";
                echo "#################\n";
                echo dbg($response);
                echo "#################\n";
            }
            throw new Exception('None 200 http response code from the API Endpoint ('.$response->code.')'."\n$http->body");
        }
        return $response;

    } // protected function _transmitRequest($request)
	/**
     * Takes the response from submitting urls for imaging and parses it out.
     * Places the responses in the appropriate places in the urlsToImage
     * array.
     *
     * @param string $response the response to process
     *
     */
    protected function _parseSubmitResponse($response)
    {
        $this->_checkContentType($response);
		if(!$response->body)exit;
		$this->databasePath = new PhotoPath($this->item->options->url);
		$this->databasePath->savePic($response->body);
		
        if ($this->debug) {
            echo "Submit Response Body is\n";
            echo "#################\n";
            echo $response->body;
            echo "#################\n";
        }

    } // protected function _parseSubmitResponse($response)
	 /**
     * finds the Content-Type in the response.
     *   XML  == Error
     *   HTML == Good.
     *
     * @param string $response
     * @return boolean
     * @throws Exception
     */
    protected function _checkContentType($response)
    {
        if (!isset($response->headers['Content-Type'])) {
            throw new Exception('No Content-Type in response.');
        }
        if ($response->headers['Content-Type'] != 'text/html') {
            throw new Exception('There was an error. Content-Type returned was '.$response->headers['Content-Type']."\n".$response);
        }

        return true;
    } // protected function _checkContentType($response)

	public function getPhotoPath(){
		return $this->databasePath->getWebPath();
	}
}